//     供应商清单
import { EllipsisOutlined, PlusOutlined } from "@ant-design/icons";
import {
  ActionType,
  ProColumns,
  ModalForm,
  ProFormText,
} from "@ant-design/pro-components";
import { ProTable } from "@ant-design/pro-components";
import { Button, message, Upload, UploadProps } from "antd";
import { useRef } from "react";
import request from "umi-request";
import axios from "../../../utils/axios";

type GithubIssueItem = {
  supAbbreviations: string;
  supId: number;
  supName: number;
  supNumber: string;
  supUpdateTime: string;
  supPhone: string;
  userId: number;
  userName: string;
};
let columns: ProColumns<GithubIssueItem>[] = [
  {
    title: "序号",
    dataIndex: "supId",
    key: "supId",
    valueType: "indexBorder",
    width: 48,
  },
  {
    title: "供方代号",
    dataIndex: "supNumber",
    key: "supNumber",
    copyable: true,
    ellipsis: true,
    filters: true,
    onFilter: true,
  },
  {
    title: "供方简称",
    dataIndex: "supAbbreviations",
    key: "supAbbreviations",
    filters: true,
    onFilter: true,
  },
  {
    title: "供方全称",
    dataIndex: "supName",
    key: "supName",
    filters: true,
    onFilter: true,
    width: 120,
    search: false,
  },
  {
    title: "供方电话",
    dataIndex: "supPhone",
    key: "supPhone",
    filters: true,
    onFilter: true,
    width: 120,
    search: false,
  },
  {
    title: "更新时间",
    key: "supUpdateTime",
    dataIndex: "supUpdateTime",
    valueType: "dateTime",
    sorter: true,
    hideInSearch: true,
  },
  {
    title: "更新人",
    dataIndex: "userName",
    key: "userName",
    width: 80,
    search: false,
  },
  {
    title: "操作",
    valueType: "option",
    key: "option",
    render: (text, record, _, action) => [
      <a
        key="editable"
        onClick={() => {
          action?.startEditable?.(record.supId);
        }}
      >
        编辑
      </a>,
      <a
        target="_blank"
        onClick={() => {
          action?.startEditable?.(record.supId);
        }}
        rel="noopener noreferrer"
        key={"view"}
      >
        删除
      </a>,
    ],
  },
];
export default () => {
  const actionRef = useRef<ActionType>();
  return (
    <ProTable<GithubIssueItem>
      rowKey={(record) => record.supId}
      columns={columns}
      actionRef={actionRef}
      cardBordered
      /* ---------------查询表格--------------- */
      request={async (params = {}, sort, filter) => {
        console.log(params);

        let x0 = "",
          x1 = "",
          x2 = "",
          x3 = "",
          x4 = "";
        if (params.supNumber != undefined) {
          x0 = params.supNumber;
        }
        if (params.supAbbreviations != undefined) {
          x1 = params.supAbbreviations;
        }
        if (params.supName != undefined) {
          x2 = params.supName;
        }
        if (params.supPhone != undefined) {
          x3 = params.supPhone;
        }
        if (params.userName != undefined) {
          x4 = params.userName;
        }
        console.log(x0, x1, x2, x3, x4);

        let data = await request(
          `/material/selectSupplier?supNumber=${x0}&supAbbreviations=${x1}&supName=${x2}&supPhone=${x3}&userName=${x4}`
        );
        data = data.data.listSupplier;
        console.log(data);

        return { data, success: true };
      }}
      /* -------------------表格的修改+ 删除+保存---------------------  */
      editable={{
        type: "multiple",
        /* 保存修改的数据 */
        onSave: async (key, row, originRow): Promise<any> => {
          console.log(key, row, originRow);
          try {
            const data = await axios({
              url: "/api3/material/updateSupplier",
              data: row,
              method: "post",
            });
            return console.log(data);
          } catch (err) {
            return console.log(err);
          }
        },
        /* 删除数据 */
        onDelete: (key, row): Promise<any> => {
          console.log(key, row);
          return axios({
            url: `/api3/material/deleteSupplier/${key}`,
            method: "post",
          })
            .then((data) => console.log(data))
            .catch((err) => console.log(err));
        },
      }}
      columnsState={{
        persistenceKey: "pro-table-singe-demos",
        persistenceType: "localStorage",
        onChange(value) {
          console.log("value: ", value);
        },
      }}
      search={{
        labelWidth: "auto",
      }}
      form={{
        // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
        syncToUrl: (values, type) => {
          if (type === "get") {
            return {
              ...values,
              created_at: [
                values.supAbbreviations,
                values.supId,
                values.supName,
                values.supNumber,
                values.supPhone,
                values.supState,
                values.supUpdateTime,
                values.userId,
                values.userName,
              ],
            };
          }
          return values;
        },
      }}
      pagination={{
        pageSize: 5,
        onChange: (page) => console.log(page),
      }}
      dateFormatter="string"
      headerTitle="高级表格"
      toolBarRender={() => [
        <div>
          <ModalForm<{
            supAbbreviations: string;
            supId: number;
            supName: string;
            supNumber: number;
            supPhone: string;
            supState: number;
            supUpdateTime: string;
            userId: number;
            userName: string;
          }>
            title="新增"
            trigger={
              <Button type="primary">
                <PlusOutlined />
                新增
              </Button>
            }
            autoFocusFirstInput
            modalProps={{
              onCancel: () => console.log("run"),
            }}
            submitTimeout={2000}
            /*           供应商新增          */

            onFinish={async (values) => {
              console.log(values);
              axios({
                url: "/api3/material/addSupplier",
                data: { ...values, userid: 1 },
                method: "post",
              })
                .then((data) => console.log(data))
                .catch((error) => console.log(error));
              message.success("提交成功");
              return true;
            }}
          >
            <ProFormText
              width="sm"
              name="supNumber"
              label="供方代号:"
              initialValue=""
            />
            <ProFormText
              name="supAbbreviations"
              label="供方简称:"
              initialValue=""
            />
            <ProFormText
              width="xs"
              name="supName"
              label="供方全称:"
              initialValue=""
            />
            <ProFormText name="supPhone" label="供方电话:" initialValue="" />
            {/*  <ProFormText name="userid" label="提交人:" initialValue="" /> */}
          </ModalForm>
        </div>,
        <div>
          <Button >
            <a href="/api3/material/downloadSuppliersTemplate">模板下载</a>
          </Button>
          <Button><a href="/api3/material/derivedSuppliersExcel">批量导出</a></Button>
          <Upload {...props} style={{ float: "left" }}>
            <Button>批量导入</Button>
          </Upload>
        </div>,
      ]}
    />
  );
};

/* 批量导入 */
const props: UploadProps = {
  name: "uploadFile",
  action: "/api3/material/addSuppliersExcel",
  headers: {
    authorization: "authorization-text",
  },
  method: "post",
  onChange(info) {
    console.log(info);
    if (info.file.status !== "uploading") {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === "done") {
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === "error") {
      message.error(`${info.file.name} 上传失败`);
    }
  },
};